﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Text.RegularExpressions;

namespace CodeHighlighter.Model
{
    public class CodeLine
    {
        public static readonly Regex KeyWord = new Regex(@"\\[^\s\{\}\]\[\.]*");
        public static readonly Regex InlineMath = new Regex(@"\$.*\$|\$.*");
        public static readonly Regex Comment = new Regex(@"%.*");
        public static readonly Regex Bracket = new Regex(@"\{|\}|\[|\]");


        public string Text { get; set; }

        public CodeLine()
        {
            Text = string.Empty;
            CodeWords = new ObservableCollection<CodeWord>();
        }

        public ObservableCollection<CodeWord> CodeWords { get; private set; }

        internal void AddCodeWord(string word)
        {

            Text += word;
            var codeWordType = DecideCodeWordType(word);
            var lastWord = CodeWords.LastOrDefault();
            if (lastWord != null && (lastWord.Type == codeWordType || IsWhiteSpacesOnly(word)))
                lastWord.Text += word;
            else
                CodeWords.Add(new CodeWord { Text = word, Type = codeWordType });
        }

        private static bool IsWhiteSpacesOnly(string word)
        {
            return word.All(c => c == ' ' || c == '\t');
        }

        private CodeWordType DecideCodeWordType(string word)
        {
            if (KeyWord.Match(word).Success)
            {
                return CodeWordType.Keyword;
            }
            else if (Bracket.Match(word).Success)
            {
                return CodeWordType.Bracket;
            }
            else if (Comment.Match(word).Success)
            {
                return CodeWordType.Comment;
            }
            else if (InlineMath.Match(word).Success)
            {
                return CodeWordType.Math;
            }
            else
            {
                return CodeWordType.Normal;
            }
        }
    }
}